package xyz.cerberu.cet.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.cerberu.cet.global.domain.FileHeaderType;
import xyz.cerberu.cet.global.domain.Global;
import xyz.cerberu.cet.global.utils.AESUtils;
import xyz.cerberu.cet.global.utils.FileUtils;
import xyz.cerberu.cet.user.domain.PictureDTO;
import xyz.cerberu.cet.user.exception.FileTypeNotConformException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author β世界
 * Created on 8:13
 * @Description 基本的图片服务实现
 */
public class SimplePictureServiceImpl implements PictureService{
    /** AES加密的密钥 **/
    private final static String AES_KEY = "NWSZLGSCQWUYSGQS";
    private final static String PICTURE_ORIGINAL_NAME = "pictureOriginalName";
    private final static String LAST_UPLOAD = "lastUpload";
    private final Global global;

    @Autowired
    public SimplePictureServiceImpl(Global global) {
        this.global = global;
    }

    /**
     * @author β世界 on 8:17 2021/4/8
     * 获取到图片的文件传输流，将文件内容存储到指定的位置
     * @param inputStream: 文件读取流
     * @param pictureDTO: 图片的dto
     * @return java.lang.String
     **/
    @Override
    public String uploadPicture(InputStream inputStream, PictureDTO pictureDTO) throws Exception {
        // 判断类型是否正确
        byte[] originalData = IOUtils.toByteArray(inputStream);
        if(!FileUtils.checkFileType(originalData, FileHeaderType.GIF,FileHeaderType.JPG,FileHeaderType.PNG)){
            // 抛出文件类型异常的错误
            throw new FileTypeNotConformException("文件类型不正确");
        }

        // 将图片存储到本地
        FileOutputStream fileOutputStream = new FileOutputStream(global.getPictureFolder()+ File.separator +pictureDTO.getFileName());
        IOUtils.write(originalData,fileOutputStream);

        // 对内容进行存储
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(PICTURE_ORIGINAL_NAME, pictureDTO.getFileName());
        jsonObject.put(LAST_UPLOAD, LocalDateTime.now().atOffset(ZoneOffset.of("+8")).toEpochSecond());
        // 返回一个经过加密的pictureId
        return AESUtils.encode(jsonObject.toString(),AES_KEY);
    }

    @Override
    public InputStream getPicture(String pictureId) throws Exception {
        // 解析pictureId
        JSONObject jsonObject = JSON.parseObject(AESUtils.decode(pictureId, AES_KEY));
        // 获取源文件名
        return new FileInputStream(global.getPictureFolder()+ File.separator +jsonObject.get(PICTURE_ORIGINAL_NAME));
    }
}